#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"

#define CONV(name) ((struct sockaddr *)(name))
using namespace LogModule;

int main(int argc, char *argv[])
{

    // ./udp_server 127.0.0.1 8080
    if (argc != 3)
    {
        std::cout << "Usage ./client_server 47.98.139.142 8080" << std::endl;
        return 1;
    }
    std::string ip = argv[1];
    uint16_t port = ::atoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create socket failed";
        return 2;
    }
    LOG(LogLevel::INFOMATION) << "create socket success";

    struct sockaddr_in inet;
    inet.sin_family = AF_INET;
    inet.sin_addr.s_addr = ::inet_addr(ip.c_str());
    inet.sin_port = ::htons(port);

    // 连接
    int n = ::connect(sockfd, CONV(&inet), sizeof(inet));
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "connect failed";
        return 3;
    }

    LOG(LogLevel::INFOMATION) << "connect  success";

    std::string message;
    while (true)
    {
        std::cout << "Please enter#";
        getline(std::cin, message);

        if(message.size()==0)
        {
            continue;
        }
        int n = ::write(sockfd, message.c_str(), message.size());
        if (n == -1)
        {
            LOG(LogLevel::ERROR) << "write failed";
            continue;
        }

        char buffer[1024];
        n = ::read(sockfd, buffer, sizeof(buffer) - 1);
        if (n == -1)
        {
            LOG(LogLevel::ERROR) << "read failed";
            continue;
        }
        buffer[n] = 0;

        std::cout << buffer << std::endl;
    }

    ::close(sockfd);
    return 0;
}